package role

import (
	"context"
	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type Logic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Logic {
	return &Logic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *Logic) Role(req *types.RoleListReq) (resp *types.RoleListResp, err error) {
	// 1.builder rpc request
	listReq := pb.RoleListReq{}
	listReq.RoleName = req.Rolename
	listReq.PageNum = int32(req.PageNum)
	listReq.PageSize = int32(req.PageSize)
	// 2.request rpc
	listPage, err := l.svcCtx.UserCenterClient.RoleList(l.ctx, &listReq)
	if err != nil {
		logx.Error("query role list from user-rpc failed:%s", err.Error())
		return nil, err
	}
	// 3.return obj
	resp = new(types.RoleListResp)
	resp.TotalPage = int(listPage.TotalPage)
	resp.CurrentPage = int(listPage.CurrentPage)
	if resp.TotalPage <= 0 {
		return resp, nil
	}
	roleInfoDataList := make([]types.RoleInfoListResp, 0)
	dataList := listPage.GetData()
	for _, v := range dataList {
		roleInfoDataList = append(roleInfoDataList, types.RoleInfoListResp{
			RoleId:     v.RoleId,
			RoleName:   v.RoleName,
			Remark:     v.Remark,
			CreateTime: v.CreateTime,
		})
	}
	resp.Data = roleInfoDataList
	return resp, nil
}
